<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>


<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">



  <meta name="description" content="axios如何发送Basic Auth"/>




  <meta name="keywords" content="axios, Basic Auth, 八一" />



  <meta name="baidu-site-verification" content="HhUstaSjr0" />



  <meta name="google-site-verification" content="UA-102975942-1" />






  <link rel="alternate" href="/atom.xml" title="八一">




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=2.6.0" />



<link rel="canonical" href="https://bay1.top/2018/02/07/axios如何发送Basic-Auth/"/>


<link rel="stylesheet" type="text/css" href="/css/style.css?v=2.6.0" />
<link rel="stylesheet" type="text/css" href="/css/prettify.css" media="screen" />
<link rel="stylesheet" type="text/css" href="/css/sons-of-obsidian.css" media="screen" />



  <link rel="stylesheet" type="text/css" href="/lib/fancybox/jquery.fancybox.css" />




  
  <script id="baidu_analytics">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?9a885cc9fb6cd7bcef579deb8efe8a70";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <script id="google_analytics">
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-102975942-1', 'auto');
        ga('send', 'pageview');
  </script>










    <title> axios如何发送Basic Auth - 八一 </title>
  </head>

  <body><div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/." class="logo">八一</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>

<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    
      <a href="/archives">
        <li class="mobile-menu-item">
          
          
            文章
          
        </li>
      </a>
    
      <a href="/tags">
        <li class="mobile-menu-item">
          
          
            标签
          
        </li>
      </a>
    
      <a href="/about">
        <li class="mobile-menu-item">
          
          
            关于/友链
          
        </li>
      </a>
    
      <a href="/search">
        <li class="mobile-menu-item">
          
          
            站内搜索
          
        </li>
      </a>
    
  </ul>
</nav>

    <div class="container" id="mobile-panel">
      <header id="header" class="header"><div class="logo-wrapper">
  <a href="/." class="logo">八一</a>
</div>

<nav class="site-navbar">
  
    <ul id="menu" class="menu">
      
        <li class="menu-item">
          <a class="menu-item-link" href="/archives">
            
            
              文章
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/tags">
            
            
              标签
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/about">
            
            
              关于/友链
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/search">
            
            
              站内搜索
            
          </a>
        </li>
      
    </ul>
  
</nav>

      </header>

      <main id="main" class="main">
        <div class="content-wrapper">
          <div id="content" class="content">
            
  
  <article class="post">
    <header class="post-header">
      <h1 class="post-title">
        
          axios如何发送Basic Auth
        
      </h1>

      <div class="post-meta">
        <span class="post-time">
          2018-02-07
        </span>
        
        
        
      </div>
    </header>

    
    
  <div class="post-toc" id="post-toc">
    <h2 class="post-toc-title">文章目录</h2>
    <div class="post-toc-content">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#axios如何发送Basic-Auth认证数据？？"><span class="toc-text">axios如何发送Basic Auth认证数据？？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#其他url如何post-Token"><span class="toc-text">其他url如何post Token???</span></a></li></ol>
    </div>
  </div>


    <div class="post-content">
      
        <p>被VUE和axios折磨的岁月,碰到404和401错误<a id="more"></a></p>
<h2 id="axios如何发送Basic-Auth认证数据？？"><a href="#axios如何发送Basic-Auth认证数据？？" class="headerlink" title="axios如何发送Basic Auth认证数据？？"></a>axios如何发送Basic Auth认证数据？？</h2><blockquote>
<p>这几天都在搞vue和flask前后端分离的小东西<br>后端采用了HTTPBasicAuth加令牌认证<br>然后写好后端接口,就用前端axios发送请求</p>
</blockquote>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//前端</span></span><br><span class="line"><span class="comment">//api.js</span></span><br><span class="line"><span class="keyword">let</span> base = <span class="string">'http://127.0.0.1:5000/api'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> requestLogin = <span class="function"><span class="params">params</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> axios.post(<span class="string">`<span class="subst">$&#123;base&#125;</span>/login`</span>, params).then(<span class="function"><span class="params">res</span> =&gt;</span> res.data);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//Login.vue</span></span><br><span class="line">    methods: &#123;</span><br><span class="line">      handleSubmit2(ev) &#123;</span><br><span class="line">        <span class="keyword">var</span> _this = <span class="keyword">this</span>;</span><br><span class="line">        <span class="keyword">this</span>.$refs.ruleForm2.validate(<span class="function">(<span class="params">valid</span>) =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">if</span> (valid) &#123;</span><br><span class="line">            <span class="keyword">this</span>.logining = <span class="literal">true</span>;</span><br><span class="line">            <span class="comment">//NProgress.start();</span></span><br><span class="line">            <span class="keyword">var</span> loginParams = &#123; name: <span class="keyword">this</span>.ruleForm2.account, password: <span class="keyword">this</span>.ruleForm2.checkPass &#125;;</span><br><span class="line">            requestLogin(loginParams).then(<span class="function"><span class="params">data</span> =&gt;</span> &#123;</span><br><span class="line">              .....</span><br><span class="line">            &#125;);</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'error submit!!'</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//后端</span></span><br><span class="line"><span class="meta">@auth</span>.verify_password</span><br><span class="line">def verify_password(name_or_token, password):</span><br><span class="line">    <span class="keyword">if</span> request.path == <span class="string">"/api/login"</span>:</span><br><span class="line">        admin = Admin.query.filter_by(name=name_or_token).first()</span><br><span class="line">        <span class="keyword">if</span> not admin or not admin.verify_password(password):</span><br><span class="line">            <span class="keyword">return</span> False</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        admin = Admin.verify_auth_token(name_or_token)</span><br><span class="line">        <span class="keyword">if</span> not admin:</span><br><span class="line">            <span class="keyword">return</span> False</span><br><span class="line">    g.admin = admin   </span><br><span class="line">    <span class="keyword">return</span> True</span><br></pre></td></tr></table></figure>
<blockquote>
<p>如上发送数据查看控制台一直报错404<br>搜了好久发现是模板问题(这里使用的是vue-admin后台模板)<br>需要注释掉mock测试数据才能进行后端接口测试<br><a href="http://blog.csdn.net/GreenHand__5564/article/details/78540843?locationNum=8&amp;fps=1" target="_blank" rel="noopener">关于axios特别说明request failed with status code 404</a></p>
</blockquote>
<p>然后继续测试,发现又报错401<br>看了下代码感觉没什么错误……<br>然后就用postman模拟了下请求,发现也是同样的错误</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">"error"</span>: <span class="string">"Unauthorized access"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后再看后端代码HTTPBasicAuth…..原谅我很少搞前后端分离<br>这个BasicAuth的接口需要特殊的发送请求<br>postman中指定auth类型就能发送成功</p>
<p><img src="https://s1.ax1x.com/2018/02/07/9lHgDU.png" alt="postman"></p>
<blockquote>
<p>转向axios查找文档发现</p>
</blockquote>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.</span></span><br><span class="line"><span class="comment">// This will set an `Authorization` header, overwriting any existing</span></span><br><span class="line"><span class="comment">// `Authorization` custom headers you have set using `headers`.</span></span><br><span class="line"><span class="attribute">auth</span>: &#123;</span><br><span class="line">  <span class="attribute">username</span>: <span class="string">'janedoe'</span>,</span><br><span class="line">  <span class="attribute">password</span>: <span class="string">'s00pers3cret'</span></span><br><span class="line">&#125;,</span><br></pre></td></tr></table></figure>
<blockquote>
<p>于是修改api.js中axios为下面的样子</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> requestLogin = <span class="function"><span class="params">params</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> axios(&#123;</span><br><span class="line">        method: <span class="string">'POST'</span>,</span><br><span class="line">        url: <span class="string">`<span class="subst">$&#123;base&#125;</span>/login`</span>,</span><br><span class="line">        auth: params</span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function"><span class="params">res</span> =&gt;</span> res.data);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>然后……还是401<br>在控制台消息头中发现Authorization的值和postman中的不一样<br>只包含了password的值,尝试修改Login.vue中loginParams的name为username<br>状态码200K…………………….<br>en………好好看文档,好好学习</p>
<p><img src="https://s1.ax1x.com/2018/02/07/9lHWE4.png" alt="咸鱼"></p>
<h2 id="其他url如何post-Token"><a href="#其他url如何post-Token" class="headerlink" title="其他url如何post Token???"></a>其他url如何post Token???</h2><blockquote>
<p>不是很清楚正确的姿势是什么,按照后端的代码<br>auth认证的方式会首先检验是否为token<br>即发送token也是同样的post格式</p>
</blockquote>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> getAdmin = <span class="function"><span class="params">params</span> =&gt;</span> &#123; </span><br><span class="line">    <span class="keyword">return</span> axios(&#123;</span><br><span class="line">        method: <span class="string">'GET'</span>,</span><br><span class="line">        url: <span class="string">`<span class="subst">$&#123;base&#125;</span>/admin`</span>,</span><br><span class="line">        auth: &#123;username: params&#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function"><span class="params">res</span> =&gt;</span> res.data);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">#params是取得的token</span><br></pre></td></tr></table></figure>
<p>这里有个点就是我按照这个方法请求之后<br>还是一直报错401,就是验证失败<br>后来才发现是前端post的token含有双引号<br>去掉之后就可以正确post了</p>

      
    </div>

    
      
      



      
      
    

    
      <footer class="post-footer">
        
          <div class="post-tags">
            
              <a href="/tags/axios/">axios</a>
            
              <a href="/tags/Basic-Auth/">Basic Auth</a>
            
          </div>
        
        
        
  <nav class="post-nav">
    
      <a class="prev" href="/2018/02/08/vue中axios如何实现token验证/">
        <i class="iconfont icon-left"></i>
        <span class="prev-text nav-default">vue中axios如何实现token验证</span>
        <span class="prev-text nav-mobile">上一篇</span>
      </a>
    
    
      <a class="next" href="/2018/02/01/Django自带认证系统邮件模板自定义/">
        <span class="next-text nav-default">Django自带认证系统邮件模板自定义</span>
        <span class="prev-text nav-mobile">下一篇</span>
        <i class="iconfont icon-right"></i>
      </a>
    
  </nav>

      </footer>
    

  </article>


          </div>
          
  <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div> 
    </div>
  </div>


        </div>
      </main>

      <footer id="footer" class="footer">

  <div class="social-links">
    
      
        
          <a href="https://github.com/bay1" class="iconfont icon-github" title="github"></a>
        
      
    
      
        
          <a href="http://weibo.com/3190704711/profile?topnav=1&wvr=6&is_all=1" class="iconfont icon-weibo" title="weibo"></a>
        
      
    
      
    
      
    
      
    
    
    
  </div>


<div class="copyright">
  <span class="copyright-year">
    
    &copy; 
     
      2016 - 
    
    2018
    <span class="author">bay1</span>
  </span>
</div>
      </footer>

      <div class="back-to-top" id="back-to-top">
        <i class="iconfont icon-up"></i>
      </div>
    </div>

    
  
  <script type="text/javascript">
    var disqus_config = function () {
        this.page.url = 'https://bay1.top/2018/02/07/axios如何发送Basic-Auth/';
        this.page.identifier = '2018/02/07/axios如何发送Basic-Auth/';
        this.page.title = 'axios如何发送Basic Auth';
    };
    (function() {
    var d = document, s = d.createElement('script');

    s.src = '//https-blog-flywinky-top-1.disqus.com/embed.js';

    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
    })();  
  </script>



    
  





  
    <script type="text/javascript" src="/lib/jquery/jquery-3.1.1.min.js"></script>
  

  
    <script type="text/javascript" src="/lib/slideout/slideout.js"></script>
  

  
    <script type="text/javascript" src="/lib/fancybox/jquery.fancybox.pack.js"></script>
  


    <script type="text/javascript" src="/js/src/even.js?v=2.6.0"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=2.6.0"></script>
<script src="/js/prettify.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $('pre').addClass('prettyprint');
   prettyPrint();
 })
</script>
  </body>
</html>
